package com.sinoglobal.shakeprize.activity.base;

import java.lang.reflect.Field;
import java.util.Stack;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sinoglobal.shakeprize.R;
import com.sinoglobal.shakeprize.annotation.InJectView;
import com.sinoglobal.shakeprize.frame.ITask;
import com.sinoglobal.shakeprize.utils.Contstent;
import com.sinoglobal.shakeprize.utils.EquipmentUtil;
import com.sinoglobal.shakeprize.utils.FlyUtil;
import com.sinoglobal.shakeprize.utils.ItktLog;
import com.sinoglobal.shakeprize.utils.SPUtil;
import com.sinoglobal.shakeprize.utils.ToastBuilder;

public abstract class AbstractActivity extends FragmentActivity {
	protected TextView title;
	public static int RESULT_DATA = 1;
	protected boolean is_run = true; // 在异步加载中是否判断网络 true: 是
	// 标题
	protected TextView titleView;
	protected ImageView templateButtonLeft; // 模板中左则Button,不使用模板时，此值为null;
	protected TextView templateButtonRight; // 模板中右则Button,不使用模板时，此值为null;
	protected ImageView microButtonRight; // 微视听使用控件
	protected LinearLayout mainBody; // 主体显示
	private Dialog dialog;
	// private ProgressDialog progressDialog;
	private Dialog messageDialog; //
	protected boolean isTemplate = true; // 是否使用模板,不使用模板时请按照模板方式编写，使用时则不需要。
	 protected RelativeLayout titleRelativeLayout;
	private boolean isShowNoValue = false;
	protected View templateView;
	private LinearLayout reLoadLayout;
	protected TextView reLoadTv;
	// private ImageView loadingIv;
	public boolean cached = false; // true为加载过缓存数据
	protected boolean scollAble = true;
	// private LinearLayout main;
	public boolean scollBack = false;
	protected String sendParams; // 请求参数
	private ProgressBar pb;
	protected boolean finishAnim;
	private ProgressDialog pd;
	private static Stack<Activity> activityStack;// activity栈
	public Activity mActivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		FlyUtil.addAppActivity(this);
		// FinalActivity.initInjectedView(this);

		mActivity = this;
		if (isTemplate) {
			setContentView(R.layout.template);
			titleRelativeLayout = (RelativeLayout)findViewById(R.id.title_iv_id);
			templateButtonLeft = (ImageView) findViewById(R.id.title_but_left);
			templateButtonRight = (TextView) findViewById(R.id.title_but_right);
			microButtonRight = (ImageView) findViewById(R.id.mico_but_right);
			// templateButtonRight.setBackgroundResource(R.drawable.button_style);
			titleView = (TextView) findViewById(R.id.title_text);
			mainBody = (LinearLayout) findViewById(R.id.view_mainBody);
			templateButtonLeft.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					finish();
				}
			});

		}

		titleView = (TextView) findViewById(R.id.title_text);
		mainBody = (LinearLayout) findViewById(R.id.view_mainBody);
		pb = (ProgressBar) findViewById(R.id.progres1);
		reLoadLayout = (LinearLayout) findViewById(R.id.load_id);
		reLoadTv = (TextView) findViewById(R.id.reLoadTv);
	}

	@Override
	public void setContentView(int layoutResID) {
		if (layoutResID == R.layout.template) {
			super.setContentView(layoutResID);
		} else {
			if (mainBody != null) {
				mainBody.removeAllViews();
				mainBody.addView(this.getLayoutInflater().inflate(layoutResID, null));
			} else {
				super.setContentView(layoutResID);
			}
		}
	}

	/**
	 * @author ty
	 * @createdate 2012-10-25 下午4:22:51
	 * @Description: 返回首页
	 */
	protected void goHome() {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		// FlyUtil.intentForward(AbstractActivity.this, HomeActivity.class,
		// intent);
		AbstractActivity.this.finish();
	}

	// 判断是否登录并跳转到登录界面
	public boolean isLoginIntentLoginActivity() {
		if (TextUtils.isEmpty(SPUtil.getString(mActivity, Contstent.USER_ID))) {
			startActivity(new Intent("com.sinoglobal.ningxia.Login"));
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			return false;
		}
		return true;
	};

	/**
	 * @author ty
	 * @createdate 2012-9-24 上午9:10:36
	 * @Description: 显示Toast消息
	 * @param message
	 */
	public void showShortToastMessage(String message) {
		ToastBuilder.getIntance(getApplicationContext()).showToast(message);
//		 Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	// /**
	// * @author sbk
	// * @createdate 2014-4-27 下午4:08:30
	// * @Description: 换背景
	// * @param type
	// *
	// */
	// public void setBg(boolean type) {
	// if (type) {
	// mainBody.setBackgroundResource(R.drawable.bg_left);
	// titleRelativeLayout.setBackgroundResource(R.drawable.night_main_top_bg);
	// } else {
	// mainBody.setBackgroundResource(R.drawable.main_bg);
	// titleRelativeLayout.setBackgroundResource(R.drawable.main_top_bg);
	// }
	// }

	/**
	 * @author sbk
	 * @createdate 2014-4-3 下午3:23:08
	 * @Description: 显示加载框
	 * 
	 */
	public void showLoading() {
		reLoadLayout.setVisibility(View.VISIBLE);
		pb.setVisibility(View.VISIBLE);
		reLoadTv.setVisibility(View.GONE);
		// logoAnimation = (AnimationDrawable) loadingIv.getBackground();
		// if (loadingHandler == null) {
		// loadingHandler = new Handler();
		// }
		// loadingHandler.postDelayed(new Runnable() {
		// public void run() {
		// logoAnimation.start(); // 开始动画
		// }
		// }, 50);

	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-10-11 上午10:22:47
	 * @description 查找id
	 * @params
	 * @return
	 * @throws Exception
	 */
	public void autoInjectAllField(Activity activity) throws IllegalAccessException, IllegalArgumentException {
		// 得到Activity对应的Class
		Class clazz = this.getClass();
		// 得到该Activity的所有字段
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			// 判断字段是否标注InjectView
			if (field.isAnnotationPresent(InJectView.class)) {
				// 如果标注了，就获得它的id
				InJectView inject = field.getAnnotation(InJectView.class);
				int id = inject.id();
				if (id > 0) {
					// 反射访问私有成员，必须加上这句
					field.setAccessible(true);
					// 然后对这个属性复制
					field.set(activity, activity.findViewById(id));
				}
			}
		}
	}

	/**
	 * @author sbk
	 * @createdate 2014-4-3 下午3:23:08
	 * @Description: 关闭加载框
	 * 
	 */
	public void dismisLoading() {
		// if (logoAnimation != null && logoAnimation.isRunning()) { //
		// 如果正在运行,就停止
		// logoAnimation.stop();
		// }
		reLoadLayout.setVisibility(View.GONE);
		ItktLog.i("关闭加载框");
	}

	/**
	 * @author sbk
	 * @createdate 2014-4-3 下午3:23:08
	 * @Description: 显示重新加载
	 * 
	 */
	public void showReLoading() {
		pb.setVisibility(View.GONE);
		reLoadLayout.setVisibility(View.VISIBLE);
		reLoadTv.setVisibility(View.VISIBLE);
	}

	@Override
	public void setContentView(View view) {
		view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		if (mainBody != null) {
			mainBody.removeAllViews();
			mainBody.addView(view);
		}

	}

	@Override
	public void setContentView(View view, LayoutParams params) {
		if (mainBody != null) {
			mainBody.removeAllViews();
			mainBody.addView(view, params);
		}
	}

	/**
	 * @author sbk
	 * @createdate 2014-5-1 下午6:03:53
	 * @Description: 弹出对话框
	 * @param message
	 * @param cancelable
	 * @param flag
	 * @param isLoadingPrompt
	 * 
	 */
	public void showWaitingDialog(String message, boolean cancelable, boolean flag, boolean isLoadingPrompt) {
		// if (null == dialog) {
		// dialog = new Dialog(this, R.style.dialog_windowFullscreen);
		// waitingView = LayoutInflater.from(((Activity) this)).inflate(
		// R.layout.view_loading, null);
		// ImageView imageView = (android.widget.ImageView) waitingView
		// .findViewById(R.id.iv_id);
		// logoAnimation = (AnimationDrawable) imageView.getDrawable();
		// dialog.setContentView(waitingView);
		// }
		//
		// if (isLoadingPrompt) { // 使用运营推荐消息
		// // message = getMessage(ItktApplication.LOADING_PROMPT);
		// if (TextUtil.stringIsNull(message)) {
		// message = this.getString(R.string.please_wait);
		// }
		// }
		//
		// if (flag) {
		// waitingView.setBackgroundResource(R.drawable.img_loading_super_bg);
		// } else {
		// waitingView.setBackgroundColor(this.getResources().getColor(
		// R.color.transparent));
		// }
		// waitingView.setBackgroundColor(this.getResources().getColor(
		// R.color.transparent));
		// waitingView.invalidate();
		// // logoAnimation.start(); //开始动画
		// // 使用Handler因为在某些手机不会转
		// if (loadingHandler == null) {
		// loadingHandler = new Handler();
		// }
		// loadingHandler.postDelayed(new Runnable() {
		// public void run() {
		// logoAnimation.start(); // 开始动画
		// }
		// }, 50);
		// // TextView textView = (TextView)
		// waitingView.findViewById(R.id.tv_id);
		// // textView.setText(message);
		// dialog.setCancelable(cancelable);
		// dialog.show();

		pd = ProgressDialog.show(this, null, message, true, cancelable);
	}

	public void dismissWaitingDialog() {
		// if (logoAnimation != null && logoAnimation.isRunning()) { //
		// 如果正在运行,就停止
		// logoAnimation.stop();
		// }
		// dialog.dismiss();
		try {
			pd.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * @author ty
	 * @createdate 2012-6-6 下午1:59:16
	 * @Description: 提示各种操作的提示语，在非UI线程操作此方法
	 * @param index
	 * @param task
	 *            回调异步操作
	 */
	@SuppressWarnings("rawtypes")
	private void showUiThreadInfo(final ITask task) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				task.exception();
			}
		});
	}

	/**
	 * @author ty
	 * @createdate 2013-1-6 上午9:54:10
	 * @Description: 没有网络提示信息
	 */
	private void notNetWorkInfo() {

		showShortToastMessage(getString(R.string.no_connections));

	}

	/**
	 * @author ty
	 * @createdate 2013-1-8 上午11:22:14
	 * @Description: 解决产品要求在特定的页面中网络不可能提示用的信息，不使用封装的intentForward方法
	 * @param context
	 * @param 类型
	 * @param intent
	 */
	protected void intentForwardNetWork(Context context, int type, Intent intent) {
		if (!EquipmentUtil.checkNetState(context)) {
			notNetWorkInfo();
			return;
		}
		FlyUtil.intentForward(context, intent);
	}

	/**
	 * @author sbk
	 * @createdate 2014-5-1 下午5:42:50
	 * @Description: 异步任务，可弹对话框
	 * @param <Params>
	 * @param <Progress>
	 * @param <Result>
	 */
	public abstract class ItktAsyncTaskWithDialog<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> implements
			ITask<Params, Progress, Result> {

		private String message = null;
		private boolean isLoadingPrompt = true; // isLoadingPrompt
		private boolean isCanceled = true;

		public ItktAsyncTaskWithDialog() {
		}

		/**
		 * @param message
		 *            提示信息
		 * @param isLoadingPrompt
		 *            是否对话框
		 * @param isCanceled
		 *            是否允许关闭
		 */
		public ItktAsyncTaskWithDialog(String message, boolean isLoadingPrompt, boolean isCanceled) {
			this.message = message;
			this.isLoadingPrompt = isLoadingPrompt;
			this.isCanceled = isCanceled;

		}

		@Override
		protected void onPreExecute() {
			if (isLoadingPrompt) {
				showWaitingDialog(message, isCanceled, false, false);
			}
			super.onPreExecute();
		}

		@Override
		protected Result doInBackground(Params... params) {
			try {
				return before(params);
			} catch (Exception e) {
				e.printStackTrace();
				showUiThreadInfo(this);
				cancel(false);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Result result) {
			super.onPostExecute(result);
			if (isLoadingPrompt) {
				dismissWaitingDialog();
			}
			after(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	/**
	 * 
	 * @author ty
	 * @createdate 2012-6-6 下午1:37:40
	 * @Description: 异步任务封装---带有ProgressDialog
	 * @param <Params>
	 *            启动任务执行的参数
	 * @param <Progress>
	 *            后台任务执行的百分比。
	 * @param <Result>
	 *            后台执行任务最终返回的结果
	 */
	public abstract class ItktOtherAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> implements
			ITask<Params, Progress, Result> {

		private boolean isShowProgressDialog = true;

		public ItktOtherAsyncTask() {
		}

		/**
		 * 不显示进度对话框
		 * 
		 * @param isShowProgressDialog
		 *            false：为不显示
		 */
		public ItktOtherAsyncTask(boolean isShowProgressDialog) {
			this.isShowProgressDialog = isShowProgressDialog;
		}

		@Override
		protected void onPreExecute() {
			if (isShowProgressDialog) {
				// showLoading();
			}
			super.onPreExecute();
		}

		@Override
		protected Result doInBackground(Params... params) {
			try {
				return before(params);
			} catch (Exception e) {
				e.printStackTrace();
				showUiThreadInfo(this);
				cancel(false);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Result result) {
			super.onPostExecute(result);
			if (isShowProgressDialog) {
				// dismisLoading();
			}
			after(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			if (isShowProgressDialog) {
			}
		}
	}

	/**
	 * @author ty
	 * @createdate 2012-10-19 上午11:28:15
	 * @Description: 显示Body显示的信息
	 * @param info
	 */
	protected void showBodyInfo(String info) {
		View view = getLayoutInflater().inflate(R.layout.template_failure, null);
		TextView textView = (TextView) view.findViewById(R.id.txt_load_fail);
		textView.setText(info);
		mainBody.removeAllViews();
		mainBody.setGravity(Gravity.CENTER);
		mainBody.addView(view);
	}

	/**
	 * @author ty
	 * @createdate 2012-10-19 下午1:55:43
	 * @Description: 列表显示数据没有
	 * @param listView
	 * @param info
	 */
	protected void showListNoValue(String info) {
		templateView = getLayoutInflater().inflate(R.layout.template_failure, null);
		TextView textView = (TextView) templateView.findViewById(R.id.txt_load_fail);
		textView.setText(info);
		if (mainBody != null) {
			mainBody.removeAllViews();
			mainBody.setGravity(Gravity.CENTER);
			mainBody.addView(templateView);
		}
	}

	/**
	 * @author ty
	 * @createdate 2012-10-19 下午1:55:43
	 * @Description: 
	 *               列表显示数据没有，这个方法用于列表无数据，可以添加数据，如果无数据就什么都不干，返回重查，直接用上面的方法showListNoValue
	 * @param listView
	 * @param info
	 */
	protected void showListNoValueChildGone(String info) {
		templateView = getLayoutInflater().inflate(R.layout.template_failure, null);
		TextView textView = (TextView) templateView.findViewById(R.id.txt_load_fail);
		textView.setText(info);
		int count = mainBody.getChildCount();
		for (int i = 0; i < count; i++) {
			View vi = mainBody.getChildAt(i);
			vi.setVisibility(View.GONE);
		}
		mainBody.setGravity(Gravity.CENTER);
		mainBody.addView(templateView);
		isShowNoValue = true;// 说明执行过现实无数据这个方法，为了有数据后判断，如果执行过这个方法，有数据后才执行showListChildVisible方法里的代码
	}

	/**
	 * @author ty
	 * @createdate 2012-10-31 下午3:44:42
	 * @Description: 查询无数据，再添加数据以后，现实出来添加的数据用此方法；
	 *               加了isShowNoValue来判断，意思是执行这个方法体的前提是一定执行过showListNoValueChildGone方法
	 */
	protected void showListChildVisible() {
		if (isShowNoValue) {
			mainBody.removeView(templateView);
			templateView = null;
			int count = mainBody.getChildCount();
			for (int i = 0; i < count; i++) {
				View vi = mainBody.getChildAt(i);
				vi.setVisibility(View.VISIBLE);
			}
			isShowNoValue = false;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	/**
	 * @author miaoxin.ye
	 * @createdate 2012-9-21 下午3:07:49
	 * @Description: 确认对话框
	 * @param context
	 *            Activity上下文
	 * @param title
	 *            对话框标题
	 * @param message
	 *            对话框消息
	 * @param btnText
	 *            按钮文本
	 */
	public void showConfirmDialog(String title, String message, String btnText) {
		if (messageDialog != null) {
			messageDialog.dismiss();
			messageDialog = null;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(btnText, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setCancelable(true);
		messageDialog = builder.create();
		messageDialog.show();
	}

	/**
	 * @author ty
	 * @createdate 2012-10-26 下午4:58:24
	 * @Description: (用一句话描述该方法做什么)
	 * @param tipTitle
	 *            dialog标题
	 * @param tipContent
	 *            dialog内容
	 * @param telphone
	 *            电话号码
	 * 
	 */
	protected void makingCall(String tipTitle, String tipContent, final String telphone) {
		showConfirmDialog(tipTitle, tipContent, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telphone));
				startActivity(intent);
			}
		});
	}

	/**
	 * @author miaoxin.ye
	 * @createdate 2012-9-24 下午3:34:26
	 * @Description: 确认对话框
	 * @param context
	 *            Activity上下文
	 * @param title
	 *            对话框标题
	 * @param message
	 *            对话框消息
	 * @param sureListener
	 *            确认监听器
	 */
	public void showConfirmDialog(String title, String message, DialogInterface.OnClickListener sureListener) {
		if (messageDialog != null) {
			messageDialog.dismiss();
			messageDialog = null;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(R.string.btn_sure_text, sureListener);
		builder.setNegativeButton(R.string.btn_cancle, null);
		builder.setCancelable(true);
		messageDialog = builder.create();
		messageDialog.show();
	}

	/**
	 * @author ty
	 * @createdate 2012-11-20 下午3:30:29
	 * @Description: 确认对话框 只有一个按钮
	 * @param title
	 *            对话框标题
	 * @param message
	 *            对话框消息
	 * @param sureListener
	 *            确认监听器
	 * 
	 */
	public void showConfirmDialogPositiveBT(String title, String message, DialogInterface.OnClickListener sureListener) {
		if (messageDialog != null) {
			messageDialog.dismiss();
			messageDialog = null;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(R.string.btn_sure_text, sureListener);
		builder.setCancelable(true);
		messageDialog = builder.create();
		messageDialog.show();
	}

	/**
	 * @author ty
	 * @createdate 2013-1-22 下午1:44:43
	 * @Description: 确认对话框 只有一个按钮 不可点击对话框以为区域
	 * @param title
	 *            对话框标题
	 * @param message
	 *            对话框消息
	 * @param sureListener
	 *            确认监听器
	 * 
	 */
	public void showConfirmDialogPositive(String title, String message, DialogInterface.OnClickListener sureListener) {
		if (messageDialog != null) {
			messageDialog.dismiss();
			messageDialog = null;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton(R.string.btn_sure_text, sureListener);
		builder.setCancelable(false);
		messageDialog = builder.create();
		messageDialog.show();
	}


	/**
	 * @author miaoxin.ye
	 * @createdate 2012-12-17 下午2:07:26
	 * @Description: 随机获取运维推广的广告语消息
	 * @param messageList
	 * @return
	 */
	/*
	 * private String getMessage(String[] messageList){ if(messageList!=null &&
	 * messageList.length>0){ Random random = new Random(); int i =
	 * random.nextInt(messageList.length-1); return messageList[i]; } return
	 * null; }
	 */

	// 停止不用的线程
	public void cancelTask(AsyncTask task) {
		if (task != null && task.getStatus() == Status.RUNNING) {
			task.cancel(true);
			task = null;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	// 退出栈顶Activity
	public void popActivity(Activity activity) {
		if (activity != null) {
			// 在从自定义集合中取出当前Activity时，也进行了Activity的关闭操作
			activity.finish();
			activityStack.remove(activity);
			activity = null;
		}
	}

	// 获得当前栈顶Activity
	public Activity currentActivity() {
		Activity activity = null;
		if (!activityStack.empty())
			activity = activityStack.lastElement();
		return activity;
	}

	// 将当前Activity推入栈中
	public void pushActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	// 退出栈中所有Activity
	public void popAllActivityExceptOne(Class<?> cls) {
		while (true) {
			Activity activity = currentActivity();
			if (activity == null) {
				break;
			}
			if (activity.getClass().equals(cls)) {
				break;
			}
			popActivity(activity);
		}
	}

	@Override
	protected void onDestroy() {
		mainBody = null;
		FlyUtil.dismissAlert(dialog);
		FlyUtil.dismissAlert(messageDialog);
		FlyUtil.removeAppActivity(this);
		// mController.unregisterListener(listener);
		super.onDestroy();
	}

	@Override
	public void finish() {
		super.finish();
		if (!finishAnim) {
			overridePendingTransition(R.anim.activity_on, R.anim.activity_off);
		}
	}
}
